function clickLink(dom) {
  return new Promise((resolve, reject) => {
    function temp(isClicked = false, timeNo) {
      const linkList = dom.querySelectorAll("a");
      const verifyDOM = document.querySelector("[data-testid=beast-core-modal]")
      if (verifyDOM) {
        clearTimeout(timeNo)
        reject();
        return
      }
      let goonFlag = false;
      let timeId
      linkList.forEach(item => {
        if (item.innerText.includes("查看")) {
          item.click();
          document.documentElement.scrollTop += (Math.random() * 10 + 50) // 127
          goonFlag = true
        }
      })
      if (goonFlag) {
        timeId = setTimeout(() => {
          temp(true, timeId)
          clearTimeout(timeId)
          // 为模拟用户操作避免呗反爬虫机制，这里时间随机
        }, 500 + Math.random() * 1500);
      } else {
        resolve(isClicked)
      }
    }
    temp();
  })
}

function extractTableData(currentPageData) {
  const arr = []
  let index = 0;
  return new Promise((resolve, reject) => {
    // 避免pdd的放爬虫校验，不能使用循环,这里改用递归
    function handle() {
      const item = currentPageData[index]
      let orderInfo = {};
      orderInfo.orderNum = item.querySelectorAll("tr")[0].innerText.match(/订单编号：(\d+-\d+)/)[1]
      const orderOtherInfoArr = item.querySelectorAll("tr")[1].querySelectorAll("td")
      //  商品信息
      const goodsInfo = orderOtherInfoArr[0].innerText.split("\n\n")
      orderInfo.goodsId = goodsInfo[1].match(/ID: (\d+)/)[1]; //商品id
      orderInfo.goodsSpecification = goodsInfo[2]; // 商品规格
      orderInfo.count = orderOtherInfoArr[2].innerText; // 数量
      const remarkInfo = orderOtherInfoArr[7].innerText.split("\n");
      if (remarkInfo.length === 4 || remarkInfo.length === 5) {
        orderInfo.remark = remarkInfo[2]
      } else {
        orderInfo.remark = ''
      }
      let timeId
      clickLink(orderOtherInfoArr[5]).then((res) => {
        const addressInfo = orderOtherInfoArr[5].innerText.split("\n");
        orderInfo.name = addressInfo[0]; // 收货人名称
        if (addressInfo.includes('隐私号')) {
          orderInfo.phone = addressInfo[3]; // 手机号
          orderInfo.address = addressInfo[5]; // 收货地址
        } else {
          orderInfo.phone = addressInfo[2]; // 手机号
          orderInfo.address = addressInfo[3]; // 收货地址
        }
        arr.push(orderInfo)
        chrome.runtime.sendMessage({ action: 'addData', orderInfo });
        if (index < currentPageData.length - 1) {
          index++;
          if (res) {
            // 有数据是新点击获取的则需要一些时间
            timeId = setTimeout(() => {
              handle()
              clearTimeout(timeId)
            }, 3000 + Math.random() * 7000);
          } else {
            // 页面有数据直接获取即可
            handle()
          }
        } else {
          console.log(arr);
          resolve(arr)
        }
      }).catch(() => {
        clearTimeout(timeId)
        reject("校验")
        return
      })
    }
    handle()

  })
}

chrome.runtime.onMessage.addListener(async (request, sender, sendResponse) => {
  if (request.action === 'getPageData') {
    const currentPageData = document.querySelectorAll("tbody")
    if (currentPageData.length > 0) {
      try {
        const data = await extractTableData(currentPageData)
        // const sheetData = [['收件人(必填)', '手机号', "收货地址", "平台订单号", "商品信息", "规格信息", "商品数量", "备注"]]
        // data.forEach(item => {
        //   sheetData.push([item.name, item.phone, item.address, item.orderNum, '', item.goodsSpecification, item.count, item.remark])
        // })
        // console.log("success", sheetData);
        chrome.runtime.sendMessage({ action: 'done' });
      } catch (error) {
        console.log(error);
      }
    }
  }
});